<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use Helper;

class SmsConfig extends ActiveRecord
{


    public static function tableName()
    {
        return '{{%sms_config}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['addtime'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['uptime']
                ]
            ],

        ];
    }

    public function rules()
    {
        return [
            [['appkey'], 'required'],
            [['interval', 'hour', 'day', 'daylimit', 'checknum', 'timeout', 'iplimit'], 'integer'],
            ['appkey', 'unique']
        ];
    }

    /**
     * 短信缓存更新
     * @return bool 返回更新结果
     */
    public static function updateConfigCache()
    {
        $cacheData = [];
        $clients = SmsConfig::find()->orderBy('appkey ASC')->asArray()->all();
        if (!empty($clients)) {
            foreach ($clients as $k => $v) {
                $cacheData[$v['appkey']] = $v;
            }
            $cacheData = json_encode($cacheData);
            Yii::$app->redis->set('smsConfigCache', $cacheData);
        }
        return true;
    }

    public static function getConfigCache($appkey)
    {
        $result = [];
        $cacheData = Yii::$app->redis->get('smsConfigCache');
        $cacheData = json_decode($cacheData, true);
        if (empty($cacheData)) {
            $config = SmsConfig::find()->where(['appkey' => $appkey])->asArray()->one();
            if (!empty($config)) {
                $result = $config;
                self::updateConfigCache();
            }
        } else if (isset($cacheData[$appkey])) {
            $result = $cacheData[$appkey];
        }
        return $result;
    }


}


?>